import axios from "axios"
import {ElMessage} from "element-plus"
// 递归处理，将id属性转换成value属性
export const idToValue = (arr) => {
    // 递归处理子节点
    const idleChildren = (obj) => {
        const children = obj.children
        obj.value = obj.id
        if (children) {
            children.map(item => {
                idleChildren(item)
            })
        }
    }
    arr.map(item => {
        idleChildren(item)
    })
    return arr
}

export const getDeptTree = () => {
    return new Promise((resolve, reject) => {
        axios.get('/system/user/deptTree').then(res => {
            const {data, code, msg} = res.data
            if (code != 200) {
                reject(msg)
                ElMessage.error(msg)
            } else {
                const options = idToValue(data)
                resolve(options)
            }
        })
    })
}

const getLeftList = (obj) => {
    const res = []
    if (Array.isArray(obj.children)) {
        obj.children.forEach(item => {
            const tmp = getLeftList(item)
            res.push(...tmp)
        })
    } else {
        res.push(obj)
    }
    return res
}

export const getStationList = () => {
    return new Promise((resolve, reject) => {
        try {
            const init = async () => {
                const res = await getDeptTree()
                const options = []
                res.map(item => {
                    options.push(...getLeftList(item))
                })
                resolve(options)
            }
            init()
        } catch (err) {
            console.log(err);
        }
    })
}

// 智能问答 
export const qaAuthorization = 'Bearer dataset-y2dGd6aNn0pqnWR22uiYEkKC'
export const qaRequest = axios.create({
    baseURL: process.env.VUE_APP_QA_API_URL,
    // baseURL: 'http://home.linwine.space:9900/v1',
    headers: {
        'Authorization': qaAuthorization
    }
})

// 安全解析JSON
export const safeJSONParse = (jsonStr) => {
    try {
        const data = JSON.parse(jsonStr);
        return data
    } catch (err) {
        console.error('解析失败', err);
        return {}
    }
}

function decodeFilename(header) {
    const match = header?.match(/filename=(?:UTF-8'')?([^;]+)/i);
    if (match && match[1]) {
        // 处理两种编码格式：
        // 1. RFC 5987标准格式：filename*=UTF-8''%E5%8A%A0...
        // 2. 传统编码格式：filename=%E5%8A%A0...
        return decodeURIComponent(match[1].replace(/^UTF-8''/i, ''));
    }
    return 'default.xlsx'; // 默认文件名
}

// 文件下载
export const download = (data, contentDisposition) => {

    try {

        var blob = new Blob([data]);
        var downloadElement = document.createElement('a');
        var href = URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = decodeFilename(contentDisposition);
        document.body.appendChild(downloadElement);
        downloadElement.click();
        setTimeout(() => {
            document.body.removeChild(downloadElement);
            URL.revokeObjectURL(href);
        }, 200)
    } catch (err) {
        console.log(err);
        ElMessage.error('导出失败')
    }
//    const reader = new FileReader()
//    // 传入被读取的blob对象
//    reader.readAsDataURL(data)
//    // 读取完成的回调事件
//    reader.onload = (e) => {
//        let a = document.createElement('a')
//        a.download = '违规数据导出.xlsx'
//        a.style.display = 'none'
//        // 生成的base64编码
//        let url = reader.result
//        a.href = url
//        document.body.appendChild(a)
//        a.click()
//        document.body.removeChild(a)
//    }
}
